package com.mayn.jst.erp.action;

import com.jfinal.plugin.activerecord.Db;
import com.mayn.jst.shop.action.ShopAction;
import com.mayn.jst.shop.model.ShopModel;

/**
 * Finance数据库操作类
 * 
 * @author Administrator
 *
 */
public class FinanceAction {

	public static Boolean saveFeeData(int shopId, String date,String cutDate, int fType,Double fee) {
		ShopModel shopModel = ShopAction.getShop(shopId);
		String shopName = shopModel.getStr("SHOP_NAME");
		int shopPlatformId = shopModel.getInt("SHOP_PLATFORM_ID");
		int shopCompanyId = shopModel.getInt("SHOP_COMPANY_ID");
		
		String fTypeName = getFeeTypeName(fType);
		String fname = date + "_" + shopName + "_" + fTypeName;
		String insertSql = "INSERT INTO `finance_general_ledger_statis` (`FGLS_DATE`,`FGLS_CUT_PAYMENT_DATE`,`FGLS_FGLT_ID`, `FGLS_NAME`, `FGLS_COST`"
				+ ",`FGLS_SHOP_ID`, `FGLS_PLATFORM_ID`, `FGLS_COMPANY_ID`"
				+ ", `FGLS_CREATE_DATETIME`, `FGLS_CREATE_EMPLOYEE_ID`"
				+ ", `FGLS_UPDATE_DATETIME`, `FGLS_UPDATE_EMPLOYEE_ID`, `FGLS_DEL`) "
				+ " VALUES (?,?,?, ?, ?, ?, ?, ?, now(), '00535', now(), '00535', 0);";
		String updateSql = "UPDATE `finance_general_ledger_statis` SET `FGLS_COST` = ?,`FGLS_UPDATE_DATETIME` = now() "
				+ " WHERE FGLS_SHOP_ID=? AND FGLS_FGLT_ID=? AND FGLS_DATE=?";
		if (checkfinanceGeneralledgerstatis(shopId, fType, date)) {
			Db.use("erp").update(updateSql, fee, shopId, fType, date);
		} else {
			Db.use("erp").update(insertSql, date,cutDate,fType, fname, fee, shopId, shopPlatformId, shopCompanyId);
		}
		return false;
	}

	public static boolean checkfinanceGeneralledgerstatis(int shopId, int fType, String date) {
		String sql = "SELECT COUNT(*) FROM finance_general_ledger_statis WHERE FGLS_SHOP_ID=? AND FGLS_FGLT_ID=? AND FGLS_DATE=?";
		int c = Db.use("erp").queryLong(sql, shopId, fType, date).intValue();
		if (c >= 1) {
			return true;
		}
		return false;
	}

	public static String getFeeTypeName(int fType) {
		String sql = "SELECT FGLT_TYPE FROM finance_general_ledger_type where FGLT_ID=?";
		return Db.use("erp").queryStr(sql, fType);
	}

}
